﻿// DigitalDesign
// Project: InformationBoard
// Developer: Baevskih Aleksandr
// Created: 13.11.2011
// Last change: 13.11.2011

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;

namespace Server
{
    // ПРИМЕЧАНИЕ. Команду "Переименовать" в меню "Рефакторинг" можно использовать для одновременного изменения имени класса "CallbackService" в коде и файле конфигурации.
    public class CallbackService : ICallbackService
    {
        DataModelContainer DataBase = new DataModelContainer();
        Server.alex.ServiceSettings Settings = new Server.alex.ServiceSettings();
        
        //Получаем директорию для скриншотов
        public string GetScreenShotsDirectory()
        {
            return Settings.ScreenshotDirectory;
        }

        //Задаем директорию для скриншотов
        public void SetScreenShotsDirectory(string Dir)
        {
            if (!Directory.Exists(Dir))
                throw new Exception(String.Format("CallBack service error: Bad directory - \"{0}\"", Dir));

            Settings.PropertyValues["ScreenshotDirectory"].PropertyValue = Dir;
            Settings.Save();
        }

        private string GeneratePath(string Root, int ClientID)
        {
            return String.Format("{0}{1}", Root, ClientID);
        }

        private string GeneratePath(string Directory, string FileName)
        {
            return String.Format("{0}\\{1}", Directory, FileName);
        }

        //Получаем скриншот от клиента
        public void GetScreenShot(int ClientID, byte[] Picture)
        {
            if ((from _clients in DataBase.ClientDevices where _clients.Id == ClientID select _clients).Count() == 0)
                throw new Exception(String.Format("CallBack service error: Bad client ID - {0}", ClientID));

            var _path = GetScreenShotsDirectory();

            ScreenShot screenShot = new ScreenShot();

            screenShot.ClientDeviceId = ClientID;
            screenShot.TimeOfShot = DateTime.Now;
            
            char[] _buf = screenShot.TimeOfShot.ToString().ToCharArray();
          
            _buf[screenShot.TimeOfShot.ToString().IndexOf(':')] = '.';
            _buf[screenShot.TimeOfShot.ToString().LastIndexOf(':')] = '.';
     
            for (int i = 0; i < _buf.Length; i++)
                screenShot.FileName += _buf[i];

            _path = GeneratePath(_path, ClientID);

            Directory.CreateDirectory(_path);

            _path = GeneratePath(_path, screenShot.FileName);

            FileStream fileStream = new FileStream(_path, FileMode.Create, FileAccess.Write);
          
            fileStream.Write(Picture, 0, Picture.Length);
            fileStream.Close();

            DataBase.AddToScreenShots(screenShot);
            DataBase.SaveChanges();
        }

        //Получаем список скриншотов на клиенте
        public List<ScreenShotWarp> GetListOfScreenShotsOnClient(int ClientID)
        {
            if ((from _clients in DataBase.ClientDevices where _clients.Id == ClientID select _clients).Count() == 0)
                throw new Exception(String.Format("CallBack service error: Bad client ID - {0}", ClientID));

            List<ScreenShotWarp> screenShots = new List<ScreenShotWarp>();

            foreach (ScreenShot tempScreenShot in DataBase.ScreenShots)
            {
                if (tempScreenShot.ClientDeviceId == ClientID)
                    screenShots.Add(new ScreenShotWarp(tempScreenShot.Id, tempScreenShot.TimeOfShot));
            }

            return screenShots;
        }

        //Удаляем скриншоты клиента
        public void DeleteScreenShots(int ClientID)
        {
            var _path = GeneratePath(GetScreenShotsDirectory(), ClientID);

            if (!Directory.Exists(_path))
                return;

            Directory.Delete(_path, true);

            foreach(ScreenShot _tempScreenShot in DataBase.ScreenShots)
            {
                if (_tempScreenShot.ClientDeviceId == ClientID)
                    DataBase.ScreenShots.DeleteObject(_tempScreenShot);
            }

            DataBase.SaveChanges();
        }

        //Удаляем скриншот по ИД
        public void DeleteScreenShot(int ScreenShotID)
        {
            ScreenShot screenShot;

            try
            {
                screenShot = (from _screenShots in DataBase.ScreenShots
                              where _screenShots.Id == ScreenShotID
                              select _screenShots).First();
            }
            catch
            {
                throw new Exception(String.Format("CallBack service error: Bad screenshot ID - {0}", ScreenShotID));
            }

            File.Delete(GeneratePath(GeneratePath(GetScreenShotsDirectory(), screenShot.ClientDeviceId), screenShot.FileName));
            DataBase.ScreenShots.DeleteObject(screenShot);
            DataBase.SaveChanges();
        }

        //Получаем ссылку на скриншот
        public string GetLinkOnScreenShot(int ScreenShotID)
        {
            ScreenShot screenShot;

            try
            {
                screenShot = (from _screenShots in DataBase.ScreenShots
                              where _screenShots.Id == ScreenShotID
                              select _screenShots).First();
            }
            catch
            {
                throw new Exception(String.Format("CallBack service error: Bad screenshot ID - {0}", ScreenShotID));
            }

            return GeneratePath(GeneratePath(GetScreenShotsDirectory(), screenShot.ClientDeviceId), screenShot.FileName);
        }
    }
}
